package com.cy.mall.service.comm.impl;

import com.cy.mall.comm.utils.JsonObjectMapper;
import com.cy.mall.model.Result;
import com.cy.mall.model.enums.IdCardType;
import com.cy.mall.service.BaseService;
import com.cy.mall.service.comm.OcrIdCardService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description 身份证ocr识别 service
 * @Author tanyilin
 * @Date 2019/6/16 15:09
 */
@Slf4j
@Service
public class AliyunOcrIdCardServiceImpl extends BaseService implements OcrIdCardService {

    @Value("${aliyun.ocr-id-card-url}")
    private String ocrIdCardUrl;
    @Value("${aliyun.app-code}")
    private String appCode;

    @Autowired
    private RestTemplate restTemplate;

    @Override
    public Result<Map<String, Object>> doOcrIdCard(String image, IdCardType idCardType) {

        //请求参数
        Map<String, String> configure = new HashMap<>();
        configure.put("side", idCardType.getValue());

        Map<String, String> params = new HashMap<>();
        params.put("image", image);
        params.put("configure", JsonObjectMapper.toJson(configure));
        String paramsJson = JsonObjectMapper.toJson(params);

        log.info("阿里云-身份证[{}]ocr识别。请求参数params: {}", image, paramsJson);

        //设置HttpHeaders、HttpEntity
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
        headers.add("Authorization", "APPCODE ".concat(appCode));

        HttpEntity<String> httpEntity = new HttpEntity<>(paramsJson, headers);
        ResponseEntity<String> responseEntity = null;
        try {
            responseEntity = restTemplate.exchange(ocrIdCardUrl, HttpMethod.POST, httpEntity, String.class);
        } catch (Exception e) {
            log.error("请求异常", e);
            return Result.fail("身份证ocr识别异常，请重新上传图片。");
        }

        log.info("statusCode = {}", responseEntity.getStatusCodeValue());
        log.info("阿里云-身份证ocr识别，回调报文={}", responseEntity.getBody());

        Map<String, Object> map = JsonObjectMapper.read(responseEntity.getBody(), Map.class);
        boolean success = Boolean.valueOf(String.valueOf(map.get("success"))).booleanValue();
        if(!success) {
            Result.fail("身份证ocr识别失败，请重新上传图片。");
        }

        return Result.success("身份证ocr识别成功", map);
    }

}
